var planCode = getQueryString("planCode");
var planId = getQueryString("planId");
var applyUnit = getQueryString("applyUnit");
var isQuery = getQueryString("isQuery");
$(function () {
    $("#jqGrid").Grid({
        url: '../toolsdemandplandetail/list?planId=' + planId,
        height: 300,
        colModel: [
            {label: '提出人', name: 'organUserName', index: 'ORGAN_USER', width: 50},
            {label: '工装编码', name: 'toolsCode', index: 'TOOLS_CODE', width: 80},
            {label: '工装名称', name: 'toolsName', index: 'NAME', width: 60},
            {label: '图号', name: 'mapNo', index: 'MAP_NO'},
            {label: '规格型号', name: 'toolsSpec', index: 'TYPE'},
            {label: '库存', name: 'stockNum', index: 'STOCK_NUM', width: 40},
            {label: '在途', name: 'transitNum', index: 'TB.TRANSIT_NUM', width: 40},
            {label: '需求', name: 'demandNum', index: 'DEMAND_NUM', width: 40},
            {
                label: '预计使用时间', name: 'planeTime', index: 'SPRD.PLANE_TIME', width: 80,
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd");
                }
            },
            {label: '计划单价', name: 'planPrice', index: 'PLAN_PRICE', width: 50},
            {label: '金额', name: 'money', index: 'PLAN_PRICE*DEMAND_NUM', width: 50},
            {name: 'transitNum', hidden: true},
            {name: 'organUser', hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}
        ],
        footerrow: true,
        loadComplete: function(data){
            $("#jqGrid").jqGrid("footerData", "set", {planPrice: '总计: ',money:data.page.userData.total});
        }
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        toolslist: {
            id: '',
            planId: planId,
            materialId: '',
            name: '',
            mapNo: '',
            type: '',
            capacity: 0,
            stockNum: 0,
            transitNum: 0,
            demandNum: 1,
            planeTime: '',
            planPrice: 0
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'change'}
            ],
            planPrice: [
                {required: true, pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})?$/, message: '只能输入不超过两位小数的数字', trigger: 'blur'}
            ]
        },
        q: {
            organMonth: '' // 编制月份
        },
        abcArray: enumsToListWithoutChange("ABC_TYPE"),
        isQuery: isQuery
    },
    methods: {
        loadToolsList: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 工装清单',
                content: '../tools/toolslistSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getTools();
                    if (!res) {
                        return;
                    }
                    vm.init();
                    vm.toolslist.materialId = res.id;
                    vm.toolslist.name = res.name;
                    vm.toolslist.mapNo = res.mapNo;
                    vm.toolslist.type = res.type;
                    vm.toolslist.capacity = res.capacity;
                    vm.toolslist.stockNum = res.stockNum;
                    vm.toolslist.transitNum = res.transitNum;
                    layer.close(index);
                }
            })
        },
        query: function () {
            vm.reload();
        },
        //进行自动计算
        doSum: function () {
            var demandNum = vm.toolslist.demandNum;
            if (demandNum <= 0) {
                demandNum = Math.abs(demandNum);
                vm.toolslist.demandNum = demandNum;
            }
            var planPrice = vm.toolslist.planPrice;
            var total = demandNum * planPrice;
            vm.toolslist.money = total;

        },
        init: function(){
            vm.toolslist = {
                id: '',
                name: '',
                mapNo: '',
                planId: planId,
                materialId: '',
                type: '',
                capacity: 0,
                stockNum: 0,
                transitNum: 0,
                demandNum: 1,
                planeTime: '',
                planPrice: 0
            };
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.init();
            this.$nextTick(() => this.$refs.materialNameInput.focus());
        },
        cancel: function () {
            // 取消在途数
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var data = getSelectedRowData('#jqGrid');
            if (data.transitNum === '0') {
                alert('在途数已为0，不需要执行该操作！');
                return;
            }
            confirm('是否确认要取消在途数？', function () {
                Ajax.request({
                    url: "../toolsdemandplandetail/cancelTransit",
                    params: {toolslistId: id},
                    type: "POST",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
            this.$nextTick(() => this.$refs.materialNameInput.focus());
        },
        saveOrUpdate: function (event) {
            var url = !vm.toolslist.id ? "../toolsdemandplandetail/save" : "../toolsdemandplandetail/update";
            //执行自动计算
            vm.doSum();
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.toolslist),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../toolsdemandplandetail/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../toolsdemandplandetail/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.toolslist = r.toolslist;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var param = {};
            if (vm.q.organMonth) {
                param.organMonth = vm.GMTToStr(vm.q.organMonth);
            }
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: param,
                page: page
            }).trigger("reloadGrid");
        },
        reloadSearch: function () {
            vm.q.organMonth = '';
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        GMTToStr: function (time) {
            var date = new Date(time)
            var month = date.getMonth() + 1;
            if (month < 10) {
                month = '0' + month;
            }
            return date.getFullYear() + '-' + month;
        }
    }
});
